//
//  MFAPMLocationMonitor.m
//  MFAPMManager
//
//  Created by zhang liyu on 2019/6/17.
//

#import "MFAPMLocationMonitor.h"

#import "MFAPMAppLifeCircleProtocol.h"

#import <CoreLocation/CLLocationManagerDelegate.h>
#import <CoreLocation/CoreLocation.h>

@interface MFAPMLocationMonitor () <CLLocationManagerDelegate, MFAPMAppLifeCircleProtocol>

@property (nonatomic, assign) BOOL isStartMonitor;
@property (nonatomic, strong) CLLocationManager *locationManager;

@property (nonatomic, copy) NSString *regionDesc;

@end

NSString *kMFAPMLocationMonitorRegionUpdateNotification = @"kMFAPMLocationMonitorRegionUpdateNotification";
@implementation MFAPMLocationMonitor

#pragma mark - Singleton

+ (instancetype)sharedInstance{
    static MFAPMLocationMonitor *locationMonitor = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        locationMonitor = [[MFAPMLocationMonitor alloc] init];
    });
    return locationMonitor;
}

#pragma mark - Life Circle

- (instancetype)init{
    self = [super init];
    if(self){
        [self configActions];
    }
    return self;
}

- (void)configActions{
    _isStartMonitor = NO;
    _regionDesc = nil;
}

#pragma mark - Monitor Control Actions

- (void)startMonitor{
    if(self.isLocationMoniteEnable){
        _isStartMonitor = YES;
        self.locationManager.delegate = self;
        [self.locationManager startUpdatingLocation];
    }
}

- (void)stopMonitor{
    _isStartMonitor = NO;
    if (_locationManager) {
        [_locationManager stopUpdatingLocation];
        _locationManager.delegate = nil;
        _locationManager = nil;
    }
}

#pragma mark - Location Delegate Actions

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置
    CLLocation *currentLocation = [locations lastObject];
    // 获取当前所在的城市名
    //根据经纬度反向地理编译出地址信息
    __weak typeof(&*self) weakSelf = self;
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error){
        __strong typeof(&*self) strongSelf = weakSelf;
        if (array.count > 0){
            CLPlacemark *placemark = [array objectAtIndex:0];
            //获取城市
            NSString *city = placemark.locality;
            if (!city) {
                //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                city = placemark.administrativeArea;
            }
            //获取国家
            NSString *country = placemark.country;
            
            //发出通知，更新地区描述信息
            strongSelf.regionDesc = [NSString stringWithFormat:@"%@ %@", country,  city];
            [[NSNotificationCenter defaultCenter] postNotificationName:kMFAPMLocationMonitorRegionUpdateNotification object:strongSelf.regionDesc];
        }
    }];
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    [self stopMonitor];
}

#pragma mark - App Life Circle Delegate Actions

- (void)appDidBecomeActive:(NSNotification *)notification{
    //当前并未开启定位监听且并未获取过区域描述信息时，进行地理定位的开启
    if(!_isStartMonitor && _regionDesc.length == 0){
        [self startMonitor];
    }
}

#pragma mark - Setter & Getter

- (CLLocationManager *)locationManager{
    if(!_locationManager){
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        _locationManager.distanceFilter = 1000.0f;
    }
    return _locationManager;
}

- (BOOL)isLocationMoniteEnable{
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    return !(kCLAuthorizationStatusDenied == status
             ||kCLAuthorizationStatusRestricted == status
             ||kCLAuthorizationStatusNotDetermined == status);
}

@end
